package cn.changeforyou.analyzer.dbParse.mybatisPlusGenerator;

import cn.changeforyou.analyzer.dbParse.DatabaseUtil;
import cn.changeforyou.utils.cons.DateTimeUtils;
import cn.changeforyou.utils.string.StringUtils;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;

import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.ArrayList;
import java.util.List;
import net.sf.jsqlparser.schema.Database;

/**
 * 直接调从mybatis-plus 获取数据库的信息 
 * @author zhyu
 * @date 2021/2/22 17:12
 */
public class MybatisPlusGeneratorUtils {

    private DatabaseUtil databaseUtil;

    public MybatisPlusGeneratorUtils(DatabaseUtil databaseUtil) {
        this.databaseUtil = databaseUtil;
    }

    public List<TableInfo> getTablesInfo(String ... tableNames) {

        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(databaseUtil.getUrl());
        dsc.setDriverName(DatabaseUtil.DRIVER);
        dsc.setUsername(databaseUtil.getUsername());
        dsc.setPassword(databaseUtil.getPassword());

        PackageConfig pc = new PackageConfig();

        TemplateConfig templateConfig = new TemplateConfig();

        StrategyConfig strategy = new StrategyConfig();
        strategy.setInclude(tableNames);
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        
        GlobalConfig gc = new GlobalConfig();
        
        boolean allTables = false;
        if(null == tableNames || tableNames.length == 0) {
            allTables = true;
        }
    
        ConfigBuilder configBuilder = new ConfigBuilder(pc, dsc, strategy, templateConfig, gc);
        List<TableInfo> tableInfoList = configBuilder.getTableInfoList();
        List<TableInfo> result = new ArrayList<>();
        for (TableInfo tableInfo : tableInfoList) {
            if (StringUtils.in(tableInfo.getName(), tableNames)) {
                result.add(tableInfo);
            }
        }
        return result;
    }
}
